import { mockStores } from "@/api/mockData/storesData";
import type { StoreInfo } from "@/Interface/StoreInfoInterface";
import Mock from 'mockjs'

// 生成随机整数
const randomInt = (min: number, max: number) => {
  const intMin = Math.ceil(min);
  const intMax = Math.floor(max);
  return Math.floor(Math.random() * (intMax - intMin + 1)) + intMin;
};

// 生成随机浮点数（保留指定位数）
const randomFloat = (min: number, max: number, fixed: number) =>
  parseFloat((Math.random() * (max - min) + min).toFixed(fixed));

// 生成节假日通用数据
const generateHolidayData = () => ({
  revenue: randomInt(100000, 250000),
  profit: randomInt(30000, 100000),
  orderCount: randomInt(800, 2000),
  customerFlow: randomInt(1000, 3000),
  revenueGrowth: `${randomFloat(10, 50, 1)}%`,
  roi: randomFloat(1, 5, 2),
  newCustomerRatio: `${randomFloat(15, 40, 1)}%`
});

// 生成评分数据
const generateRating = () => {
  const rawValue = randomFloat(3.5, 5.0, 2);
  return Math.min(5.0, rawValue).toFixed(1)
};

// 生成9位唯一ID
const generateUnique9DigitId = (existingIds: string[]): string => {
  const idSet = new Set(existingIds); // 使用Set提升性能
  let id: string;
  let attempts = 0;
  do {
    // 生成100,000,000 ~ 999,999,999范围的9位数字
    id = Math.floor(100000000 + Math.random() * 900000000).toString();
    attempts++;
    // 防止极端情况下的死循环
    if (attempts > 1000) {
      throw new Error("无法生成唯一ID，请检查数据量");
    }
  } while (idSet.has(id));

  return id;
};

// 生成开业日期
const generateOpeningDate = () => {
  // 定义时间范围
  const startDate = new Date('2015-01-01').getTime();
  const endDate = new Date('2023-12-31').getTime();
  // 生成随机时间戳
  const randomTimestamp = randomInt(startDate, endDate);
  // 格式化为日期字符串
  return new Date(randomTimestamp).toISOString().split('T')[0];
};

// 基本信息
export const generateBasicData = () => {
  const fullCity = Mock.Random.city(true);
  const [province, city] = fullCity.split(' ');

  return {
    storeId: generateStoreId(),
    storeName: `${province}${city}${['分', '东', '南', '西', '北', '一', '二', '三', '四', '五'].at(randomInt(0, 9))}店`,
    province: province,
    city: city,
    coordinates: {
      lng: randomFloat(105.0, 123.0, 4),
      lat: randomFloat(20.0, 40.0, 4)
    },
    storeType: ['直营', '加盟'].at(randomInt(0, 1)),
    areaSize: randomInt(80, 300),
    openingDate: generateOpeningDate(),
    tags: [['商业区', '社区', '学校', '景区', '交通枢纽'].at(randomInt(0, 4))]
  }
}


export const generateStoreData = (storeInfo: any) => {

  // 生成每日数据
  const generateDailyData = () => {
    const baseSales = randomInt(30000, 80000);
    const startDate = new Date('2024-01-01');

    return Array.from({ length: 366 }, (_, index) => {
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + index);

      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');

      return {
        date: `${year}-${month}-${day}`,
        revenue: {
          amount: randomInt(baseSales * 0.9, baseSales * 1.1),
          yoy: `${randomFloat(-5, 15, 1)}%`,
          mom: `${randomFloat(-8, 10, 1)}%`,
          target: baseSales
        },
        profit: randomInt(8000, 35000),
        orderCount: randomInt(150, 600),
        customerFlow: randomInt(200, 800)
      };
    });
  };

  // 生成月度数据
  const generateMonthlyData = () =>
    Array.from({ length: 12 }, (_, month) => ({
      month: month + 1,
      costs: {
        total: randomInt(200000, 800000),
        ingredients: randomInt(80000, 300000),
        labor: randomInt(50000, 200000),
        operation: randomInt(30000, 150000),
        energy: randomInt(10000, 50000),
        maintenance: randomInt(5000, 30000),
        financial: randomInt(10000, 80000)
      },
      membership: {
        consumptionRatio: `${randomFloat(20, 60, 1)}%`,
        newMembers: randomInt(50, 300),
        repurchaseRate: `${randomFloat(15, 45, 1)}%`
      },
      deliveryRatio: `${randomFloat(15, 55, 1)}%`,
      staffEfficiency: randomFloat(500, 2000, 0),
      areaEfficiency: randomFloat(50, 200, 1),
      tableTurnover: randomFloat(1.5, 4.5, 1),
      staffCount: randomInt(8, 20)
    }));

  // 生成年度数据
  const generateAnnualData = () => ({
    promotions: {
      springFestival: generateHolidayData(),
      laborDay: generateHolidayData(),
      nationalDay: generateHolidayData(),
      summer: generateHolidayData()
    },
    avgCustomerValue: randomInt(35, 85),
    rating: generateRating(),
    reviews: {
      positive: randomInt(500, 2000),
      negative: randomInt(0, 50)
    },
    yearGrowth: `${randomFloat(4, 9, 1)}%`
  });

  // 赋值到目标对象
  storeInfo.dailyData = generateDailyData();
  storeInfo.monthlyData = generateMonthlyData();
  storeInfo.annualData = generateAnnualData();


  //月营业额
  // 初始化按月营业额汇总对象
  const monthlyRevenue = {} as { [key: number]: number };
  // 计算各月营业额总和
  storeInfo.dailyData.forEach((day: any) => {
    const month = parseInt(day.date.split('-')[1], 10); // 提取月份数字
    monthlyRevenue[month] = (monthlyRevenue[month] || 0) + day.revenue.amount;
  });
  // 将月营业额添加到monthlyData
  storeInfo.monthlyData.forEach((monthData: any) => {
    monthData.totalRevenue = monthlyRevenue[monthData.month] || 0;
  });

  // 年营业额
  // const sum = storeInfo.dailyData.reduce((acc: any, day: any) => {
  //   return acc + (day.revenue.amount || 0)
  // }, 0)

  // 年营业额计算
  const annualSum = storeInfo.monthlyData.reduce((sum: any, m: any) => sum + m.totalRevenue, 0);
  storeInfo.annualData.yearAmount = annualSum

  return storeInfo;
};

export const generateStoreId = () => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores
  // 获取所有现有店铺ID（处理空数据情况）
  const existingIds = storesList.map((store: StoreInfo) => store.basicInfo.storeId) || [];
  // 生成唯一9位ID并赋值
  return generateUnique9DigitId(existingIds);
}


export const MockData = () => {

  // 创建初始门店信息（用户输入部分）
  // const initialStoreInfo: any = {
  //   basicInfo: {
  //     storeId: "120000200",
  //     storeName: "北京市总店",
  //     province: "北京",
  //     city: "北京市",
  //     coordinates: {
  //       lng: "116.46541",
  //       lat: "39.92067"
  //     },
  //     storeType: "直营",
  //     areaSize: 112,
  //     openingDate: "2015-03-05",
  //     tags: ["商业区"]
  //   },
  //   dailyData: [],
  //   monthlyData: [],
  //   annualData: null
  // };

  // 生成完整门店数据
  const store = generateStoreData(generateBasicData);
  console.log(store);

}